﻿using JinYuan.DAL;
using JinYuan.Helper;
using JinYuan.MES;
using JinYuan.Models;
using PLC;
using PLC.PLCAlarm;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Linq;

namespace JinYuan.VirtualDataLibrary
{
    public class CommonMethods
    {
        /// <summary>
        /// 本地数据库
        /// </summary>
        public static ISugarHepler db = new SQLSugarService();
        /// <summary>
        /// 远程服务段数据库
        /// </summary>
        public static ISugarHepler dbServer = new SQLSugarService();
        /// <summary>
        /// 全局的PLC链接
        /// </summary>
        public static List<PlcReadWriteBase> plcDevices;
        /// <summary>
        /// plc状态
        /// </summary>
        public static readonly Dictionary<PlcReadWriteBase, Dictionary<string, object>> plcStatuses = new Dictionary<PlcReadWriteBase, Dictionary<string, object>>();
        /// <summary>
        /// 报警
        /// </summary>
        public static AlarmManager alarmManager = new AlarmManager();
        /// <summary>
        /// MES接口
        /// </summary>
        public static IMes hbgMes = new MesDataProcess();
        /// <summary>
        /// 参数
        /// </summary>
        public static ProductModelParam parRange = new ProductModelParam();
        /// <summary>
        /// 全局钩子
        /// </summary>
        public static ScanerHook listener = new ScanerHook();

        /// <summary>
        /// 创建个全局焊接功率队列数据存储
        /// </summary>
        public static List<Queue<double>> QWeldingPowerData = new List<Queue<double>>();

        /// <summary>
        /// 创建个全局入壳推力队列数据存储
        /// </summary>
        public static List<Queue<double>> QPlanenessData = new List<Queue<double>>();

        /// <summary>
        /// 创建全局的登录对象
        /// </summary>
        public static SysAdmin currentAdmin = null;
        /// <summary>
        /// 登录是否成功
        /// </summary>
        public static bool IsLoginOk = false;

        //创建一个全局的配置对象
        public static SysConfig sysConfig = new SysConfig();




        public static int InvadTime;

        /// <summary>
        /// 智能电表
        /// </summary>
        public static List<ElectricEnergy> listElectricEnergy = new List<ElectricEnergy>();

        /// <summary>
        /// 电能表
        /// </summary>
        public static EnergyMeterHelper energyMeter = new EnergyMeterHelper();

        /// <summary>
        ///是否开启刷新
        /// </summary>
        public static bool isRefreshTimerWeeding = false;

        /// <summary>
        /// SQL语句
        /// </summary>
        public static DBSQL dBSQL { get; } = new DBSQL();

        public static M_DBCtrl m_DBCtrl { get; } = new M_DBCtrl();

        /// <summary>
        /// MES配置文件类
        /// </summary>
        public static MesConfig mesConfig = new MesConfig();

        ///创建一个全局的连接状态
        public static bool connectState = false;

        /// <summary>
        /// 滴答次数
        /// </summary>
        public static int tickCount = 0;
        /// <summary>
        /// QIEHUAN
        /// </summary>
        public static int tickHomeCount = 0;
        /// <summary>
        /// 报警信息
        /// </summary>
        public static string SlideAlarmText = "当前无报警";
        /// <summary>
        /// 退出
        /// </summary>
        public static bool IsExit = false;
        /// <summary>
        /// 是否登出账户
        /// </summary>
        public static bool LoginOut = false;
        /// <summary>
        /// 是否上传MES
        /// </summary>
        public static bool IsUpMes { get; set; }
        /// <summary>
        /// 是否运行
        /// </summary>
        public static bool IsRun { get; set; } = false;
        /// <summary>
        /// 上一次设备状态
        /// </summary>
        public static int DeviceStatus = 0;
        /// <summary>
        /// 上一次Guid
        /// </summary>
        public static string DeviceGuid = "";
        /// <summary>
        ///第一次读取
        /// </summary>
        public static bool IsFirst = false;
        /// <summary>
        /// 焊接功率波形图显示条数
        /// </summary>
        public static int ChatLineCount = 3;
        /// <summary>
        /// 员工号
        /// </summary>
        public static string strWorker { get; set; }
        /// <summary>
        /// 是否开启智能电表
        /// </summary>
        public static bool IsStartZNDB { get; set; } = false;
        /// <summary>
        /// 白夜班
        /// </summary>
        public static string strClass { get; set; } = "白班";
        /// <summary>
        /// 时间变更
        /// </summary>
        public static string ChangeClassTime { get; set; } = "20:30:00";
        /// <summary>
        /// 设备状态
        /// </summary>
        public static List<bool> Statues { get; set; }

        /// <summary>
        /// 服务器链接状态
        /// </summary>
        public static bool EMCStatues { get; set; }

        #region  小时产能
        /// <summary>
        /// 上个时间点的总数
        /// </summary>
        public static int LastTotalNum { get; set; } = 0;
        /// <summary>
        /// 上个时间点良品数
        /// </summary>
        public static int LastOkNum { get; set; } = 0;
        /// <summary>
        /// 上一次重置计数的时间
        /// </summary>
        public static string LastResetTime { get; set; }
        /// <summary>
        ///  上一次的小时
        /// </summary>
        public static int LastHour { get; set; }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        public static List<Group> ListOmronGroups { get; set; }

        /// <summary>
        /// 12小时产能
        /// </summary>
        public static List<Chart12HourData> Lst_Prod12HourData = new List<Chart12HourData>();
        /// <summary>
        /// 不良选项(检测项不良)
        /// </summary>
        public static List<ChartDataType> Lst_DefectTypeQty = new List<ChartDataType>();

        /// <summary>
        /// PLC报警前10项
        /// </summary>
        public static List<ChartDataType> Lst_AlarmTop10_Qty = new List<ChartDataType>();
        /// <summary>
        /// 参数项设置
        /// </summary>
        public static List<ParamList> paramlists { get; set; }

        /// <summary>
        /// 线程控制
        /// </summary>
        public static ManualResetEvent ResetEventRecv = new ManualResetEvent(true);


        #region 计数项
        /// <summary>
        /// 生产总数
        /// </summary>
        public static float TotalQty = 0;

        public static float ProOKQty = 0;

        public static float Ppm = 0;

        public static double JiaDL = 0.0;

        public static List<float> AntiDustAirSpeed = new List<float>();
        /// <summary>
        /// PLC开机/运行时间
        /// </summary>
        public static List<int> PlcOpenAndRunTime = new List<int>();
        /// <summary>
        ///  PLC开机/运行时间地址
        /// </summary>
        public static List<string> PlcOpenAndRunTimeAdress = new List<string> { "D50", "D52", "D54", "D56", "D58", "D60" };
        public static int ProdGaoRFIDNgQty = 0;//高托杯 绑定卷心码
        public static int ProdDiRFIDNgQty = 0;//低托杯 绑定钢壳码

        public static int ProdGangKeRFIDNgQty = 0;//钢壳托杯 绑定出站钢壳码
        public static int ProdJuanBarNgQty = 0;
        public static int ProdGangKeBarNgQty = 0;

        public static int ProdRuKeTuiliNgQty = 0;
        public static int ProdCCDNgQty = 0;
        public static int ProdMesOutNGQty = 0;
        #endregion

        #region 配置信息
        public static string devPath = Application.StartupPath + "\\Config\\Device.ini";
        public static string groupPath = Application.StartupPath + "\\Config\\Group.xlsx";
        public static string variablePath = Application.StartupPath + "\\Config\\Variable.xlsx";
        public static string settingPath = Application.StartupPath + "\\Config\\settings.json";


        /// <summary>
        /// 错误日志路径
        /// </summary>
        public static string strErrorLogspath = System.Windows.Forms.Application.StartupPath + "\\Logs\\ErrorLogs";

        public static string strSystemLogspath = System.Windows.Forms.Application.StartupPath + "\\Logs\\SystemLogs";
        public static string strAlarmLogspath = System.Windows.Forms.Application.StartupPath + "\\Logs\\AlarmLogs";

        public static string strsqlLogspath = "";
        /// <summary>
        /// 删除路径
        /// </summary>
        public static string strDeletepath = "";
        /// <summary>
        /// 能耗保存路径
        /// </summary>
        public static string strWattrMeterpath = System.Windows.Forms.Application.StartupPath + "\\智能电表数据";
        /// <summary>
        /// MES路径日志
        /// </summary>
        public static string strMesLogspath = System.Windows.Forms.Application.StartupPath + "\\Logs\\MesLogs";
        /// <summary>
        /// 设备状态信息路径
        /// </summary>
        public static string strDeviceStatusPath = System.Windows.Forms.Application.StartupPath + "\\Config\\DeviceStatus.cfg";


        /// <summary>
        /// PLC读取寄存器配置文件路径
        /// </summary>
        public static string ConfigPath = Path.Combine(System.Windows.Forms.Application.StartupPath, "ini\\PlcConfig.ini");
        /// <summary>
        /// 系统程序配置文件路径
        /// </summary>
        //public static string iniFilePath = Path.Combine(System.Windows.Forms.Application.StartupPath, "ini\\Configure.ini");

        public static string xmlFilePath = Path.Combine(System.Windows.Forms.Application.StartupPath, "Config\\Configure.xml");
        /// <summary>
        /// 配置文件字典
        /// </summary>
        public static Dictionary<string, Dictionary<string, string>> Configxml = new Dictionary<string, Dictionary<string, string>>();


        #region 读取配置文件

        // 读取 XML 配置文件
        public static Dictionary<string, Dictionary<string, string>> ReadXmlConfig(string filePath)
        {
            var config = new Dictionary<string, Dictionary<string, string>>();
            XDocument xmlDoc = XDocument.Load(filePath);

            foreach (var sectionElement in xmlDoc.Root.Elements())
            {
                string sectionName = sectionElement.Name.LocalName;
                config[sectionName] = new Dictionary<string, string>();

                foreach (var keyElement in sectionElement.Elements())
                {
                    string key = keyElement.Name.LocalName;
                    string value = keyElement.Value;
                    config[sectionName][key] = value;
                }
            }

            return config;
        }

        // 获取配置值
        public static string GetConfigValue(Dictionary<string, Dictionary<string, string>> config, string section, string key, string defaultValue)
        {
            if (config.ContainsKey(section) && config[section].ContainsKey(key))
            {
                return config[section][key];
            }
            return defaultValue;
        }


        // 写入 XML 文件
        public static void WriteXmlFile(Dictionary<string, Dictionary<string, string>> config, string filePath)
        {
            XDocument xmlDoc = new XDocument(new XElement("Configuration"));

            foreach (var section in config)
            {
                var sectionElement = new XElement(section.Key);
                foreach (var keyValue in section.Value)
                {
                    sectionElement.Add(new XElement(keyValue.Key, keyValue.Value));
                }
                xmlDoc.Root.Add(sectionElement);
            }
            xmlDoc.Save(filePath);
        }

        /// <summary>
        /// 单个配置数据保存
        /// </summary>
        /// <param name="INFO"></param>
        /// <param name="Type"></param>
        /// <param name="value"></param>
        public static void UpdateConfig(string INFO, string Type, string value)
        {
            // 更新 Configxml 中的 SteelshellCount
            CommonMethods.Configxml[INFO][Type] = value;

            // 将更新后的 Configxml 写入文件
            CommonMethods.WriteXmlFile(CommonMethods.Configxml, CommonMethods.xmlFilePath);
        }












        /// <summary>
        ///读取配置文件
        /// </summary>
        public static SysConfig GetSysConfig()
        {
            try
            {

                #region 系统配置文件
                return sysConfig = new SysConfig
                {
                    AutoStart = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "AutoStart", "false")),
                    AutoLogin = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "AutoLogin", "false")),
                    AutoLock = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "AutoLockScreen", "false")),
                    LockPeriod = Convert.ToInt32(GetConfigValue(Configxml, "CONFIG_INFO", "LockIntervalTime", "0")),
                    AutoQieHuanM = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "AutoSwitchMonitor", "false")),
                    QieHuanMPeriod = Convert.ToInt32(GetConfigValue(Configxml, "CONFIG_INFO", "SwitchMonitorInterval", "0")),
                    ShowSeriesCount = Convert.ToInt32(GetConfigValue(Configxml, "CONFIG_INFO", "CurveDisplayCount", "0")),
                    SwipeCardMode = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "EnableCardMode", "false")),
                    MesModeSwitching = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "MESModeSwitch", "false")),
                    GetMesParam = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "FetchMESParams", "false")),
                    SaveThreadTime = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "SaveThreadTimeLog", "false")),
                    IsDebugMode = Convert.ToBoolean(GetConfigValue(Configxml, "CONFIG_INFO", "IsDebugMode", "false"))
                };
                #endregion
            }
            catch (Exception)
            {
                return sysConfig = null;
            }
        }

        /// <summary>
        /// 获取MES配置文件
        /// </summary>
        public static MesConfig GetMesConfig()
        {
            try
            {
                #region MES配置文件
                return mesConfig = new MesConfig
                {
                    siteCode = GetConfigValue(Configxml, "MES_CONFIG", "SiteCode", "49J"),
                    lineCode = GetConfigValue(Configxml, "MES_CONFIG", "LineCode", "PW-491"),
                    equipNum = GetConfigValue(Configxml, "MES_CONFIG", "EquipNum", "491VIM01"),
                    MESURLAddressIP = GetConfigValue(Configxml, "MES_CONFIG", "MESURLAddressIP", "10.100.111.81"),
                    MESURLAddressPort = GetConfigValue(Configxml, "MES_CONFIG", "MESURLAddressPort", "80"),
                    EmployeeAuthCheck = GetConfigValue(Configxml, "MES_CONFIG", "EmployeeAuthCheck", "491VIM01"),
                    MaterialInputInfo = GetConfigValue(Configxml, "MES_CONFIG", "MaterialInputInfo", "491VIM01"),
                    DeviceParamRequest = GetConfigValue(Configxml, "MES_CONFIG", "DeviceParamRequest", "491VIM01"),
                    DeviceParamChange = GetConfigValue(Configxml, "MES_CONFIG", "DeviceParamChange", "491VIM01"),
                    ProductInStation = GetConfigValue(Configxml, "MES_CONFIG", "ProductInStation", "491VIM01"),
                    ProductProcessParams = GetConfigValue(Configxml, "MES_CONFIG", "ProductProcessParams", "491VIM01"),
                    ProductResultParams = GetConfigValue(Configxml, "MES_CONFIG", "ProductResultParams", "491VIM01"),
                    ProductOutStation = GetConfigValue(Configxml, "MES_CONFIG", "ProductOutStation", "491VIM01"),
                    DeviceAlarm = GetConfigValue(Configxml, "MES_CONFIG", "DeviceAlarm", "491VIM01"),
                    DeviceStatus = GetConfigValue(Configxml, "MES_CONFIG", "DeviceStatus", "491VIM01"),
                    EnergyConsumption = GetConfigValue(Configxml, "MES_CONFIG", "EnergyConsumption", "491VIM01"),
                    Anemometer = GetConfigValue(Configxml, "MES_CONFIG", "Anemometer", "491VIM01"),
                };


                #endregion
            }
            catch (Exception)
            {
                return mesConfig = null;
            }
        }
        #endregion

        #region 保存配置文件
        /// <summary>
        /// 保存启动自动登录
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoStart(bool value)
        {
            Configxml["CONFIG_INFO"]["AutoStart"] = value.ToString(); // 修改自动登录为 True
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }
        /// <summary>
        /// 保存开机自动启动
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoLogin(bool value)
        {
            Configxml["CONFIG_INFO"]["AutoLogin"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }

        /// <summary>
        /// 保存无操作自动锁屏
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoLock(bool value)
        {
            Configxml["CONFIG_INFO"]["AutoLockScreen"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }

        /// <summary>
        /// 保存锁屏间隔时间
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveLockPeriod(int value)
        {
            Configxml["CONFIG_INFO"]["LockIntervalTime"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }


        /// <summary>
        /// 保存无操作自动切换监控界面
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveAutoQieHuanM(bool value)
        {
            Configxml["CONFIG_INFO"]["AutoSwitchMonitor"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }


        /// <summary>
        /// 保存无操作自动切换监控界面
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveIsDebug(bool value)
        {
            Configxml["CONFIG_INFO"]["IsDebugMode"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }

        /// <summary>
        /// 保存切换监控界面间隔时间
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveQieHuanMPeriod(int value)
        {
            Configxml["CONFIG_INFO"]["SwitchMonitorInterval"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }

        /// <summary>
        /// 保存曲线显示数量
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveShowSeriesCount(int value)
        {
            Configxml["CONFIG_INFO"]["CurveDisplayCount"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }

        /// <summary>
        /// 开启刷卡模式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveSwipeCardMode(bool value)
        {
            Configxml["CONFIG_INFO"]["EnableCardMode"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }
        /// <summary>
        /// MES/非MES模式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveOpenMesModel(bool value)
        {
            Configxml["CONFIG_INFO"]["MESModeSwitch"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }

        /// <summary>
        /// 获取MES参数
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveGetMesParam(bool value)
        {
            Configxml["CONFIG_INFO"]["FetchMESParams"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }

        /// <summary>
        /// 保存线程耗时操作
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveSaveThreadTime(bool value)
        {
            Configxml["CONFIG_INFO"]["SaveThreadTimeLog"] = value.ToString();
            WriteXmlFile(Configxml, xmlFilePath);
            return true;
        }
        #endregion

        #endregion

        #region 委托信息
        //创建委托
        // 数据监视委托
        public static Action<int, string> AddDataMonitorDelegate;
        /// <summary>
        /// 系统日志
        /// </summary>
        public static Action<bool, string> AddLogDelegate;
        /// <summary>
        /// 操作日志
        /// </summary>
        public static Action<bool, string> AddOPLogDelegate;
        /// <summary>
        /// 报警日志
        /// </summary>
        public static Action<SysLog> AddAlarmDelegate;
        /// <summary>
        /// 参数更新
        /// </summary>
        public static Action ChangeParamDelegate;
        /// <summary>
        /// 
        /// </summary>
        public static Action<bool> AddHomeDelegate;

        /// <summary>
        /// 显示上料信息
        /// </summary>
        public static Action<List<AGearEntity>> ShowFeedingDelegate;
        /// <summary>
        /// 显示钢壳信息
        /// </summary>
        public static Action<List<CGearEntity>> ShowSteelShellDelegate;
        /// <summary>
        /// 显示下料数据
        /// </summary>
        public static Action<List<BGearEntity>> ShowBlankingDelegate;
        /// <summary>
        /// 显示结构件料盘信息
        /// </summary>
        public static Action<List<DGearEntity>> ShowMaterialDelegate;
        /// <summary>
        /// 数据监视委托
        /// </summary>
        /// <param name="type"></param>
        /// <param name="info"></param>
        public static void AddDataMonitorLog(int type, string info)
        {
            //调用委托
            if (AddDataMonitorDelegate != null)
            {
                AddDataMonitorDelegate(type, info);
            }
        }

        /// <summary>
        /// 写入系统日志
        /// </summary>
        /// <param name="isError">是否为错误信息</param>
        /// <param name="info">日志信息</param>
        public static void AddLog(bool isError, string info)
        {
            //调用委托
            if (AddLogDelegate != null)
            {
                AddLogDelegate(isError, info);
            }
        }
        /// <summary>
        /// 写入操作日志
        /// </summary>
        /// <param name="isError"></param>
        /// <param name="info"></param>
        public static void AddOPLog(bool isError, string info)
        {
            //调用委托
            if (AddLogDelegate != null)
            {
                AddOPLogDelegate(isError, info);
            }
        }

        public static void AddAlarmLog(SysLog sysLog)
        {
            //调用委托
            if (AddAlarmDelegate != null)
            {
                AddAlarmDelegate(sysLog);
            }
        }

        public static void ChangeParamData()
        {
            //调用委托
            if (ChangeParamDelegate != null)
            {
                ChangeParamDelegate();
            }
        }
        #endregion

        /// <summary>
        /// TODO PLC变量集合
        /// KEY = VarAddress
        /// </summary>
        public static ConcurrentDictionary<string, PLCGroupVariable> PLCVariable = new ConcurrentDictionary<string, PLCGroupVariable>();

    }
}
